const express = require('express');
const path = require('path');      //系统路径模块
const db = require('./db/connect'); // 链接数据库
const router = require('./routes/index'); // 引入路由
// const exphbs = require('express-handlebars');  // 引入express-handlebars模块

var session = require('express-session');
var cookieParser = require('cookie-parser');
const app = express();              //实例

app.use(express.json()) //解析接口传参
app.use(express.urlencoded({ extended: false }))

//静态资源托管中间件
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('node_modules'))

//解决跨域问题
app.use(require('cors')());


//设置引擎模块
app.set('views', __dirname, 'public/views');
app.engine('html', require('consolidate').handlebars);
app.set('view engine', 'html');

// session
app.use(cookieParser());
app.use(session({
  secret: 'keyboard cat',
  name:'token',
  cookie:{
    maxAge: 60 * 1000 * 30,
    secure: false
  },
  resave: false,
  rolling: true,
  saveUninitialized: true,
}));

//使用路由 / 是路由指向名称
app.use('/', router)

// Errors => page not found 404
app.use((req, res, next) => {
  var err = new Error('Page not found');
  err.status = 404;
  next(err);
})

// Handling errors (send them to the client)
app.use((err, req, res, next) => {
  res.status(err.status || 500);
  res.send(err.message);
});

//配置服务端口 
var server = app.listen(3000, () => {
  const hostname = 'localhost';
  const port = 3000;
  console.log(`Server running at http://${hostname}:${port}/`);
})

module.exports = app;